<template>
  <div class="contract-view" v-loading="showLoading || pageLoading">
    <div v-if="!buttonAuth.check">
      <no-auth></no-auth>
    </div>
    <!--  顶部 S -->
    <template v-if="buttonAuth.check">
      <div class="contract-view-title">
        <!-- 左边按钮 -->
        <div class="contract-view-title-left">
          <el-button
            type="plain-third"
            @click="handleEdit"
            v-if="editBtnAuth"
          >
            <i class="iconfont icon-edit-square"></i>{{$t('common.base.edit')}}
          </el-button>
          <el-button
            type="plain-third"
            @click="handleClickDelete"
            v-if="buttonAuth.deleted"
          >
            <i class="iconfont icon-delete"></i>{{$t('common.base.delete')}}
          </el-button>
          <el-button
            type="plain-third"
            @click="handleClickClose"
            v-if="closeBtnAuth"
          >
            <i class="iconfont icon-close1"></i>{{$t('common.base.close')}}
          </el-button>
        </div>

        <!-- 右边按钮 -->
        <div class="contract-view-title-right">
          <el-dropdown trigger="click" v-if="planBtnAuth && !isShowCreateSmartPlan">
            <el-button type="primary"
              ><i class="iconfont icon-add2"></i>{{$t('common.base.scheduledTasks')}}</el-button
            >

            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-for="task in taskTypes" :key="task.id">
                <a
                  class="plan-dropdown-item"
                  href="javascript:;"
                  @click.prevent="jumpTaskPlan(task.id)"
                >
                  {{ task.name }}
                </a>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>

          <el-button
            v-if="calendarBtnAuth"
            class="ml_12"
            type="primary"
            @click="JumpCalendar"
            >
              <i class="iconfont icon-add2"></i>{{$t('common.base.scheduleReminder')}}
            </el-button>
          
          <!-- 更多操作 -->
          <el-dropdown class="ml_12" v-if="isShowMoreOperation" @command="handleMoreOperationCommand" trigger="click">
            <el-button type="primary">
              {{ $t('common.base.more') }} <i class="iconfont icon-fdn-select"></i>
            </el-button>
            <el-dropdown-menu class="detail-more-dropdown-menu" slot="dropdown">
              <el-dropdown-item v-if="isShowCreateSmartPlan" command="smartPlan" >{{ $t('smartPlan.title') }}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
      <!--  顶部 E -->
      <BaseTileLayoutTabBar
        :bar-list="taskLayoutTabBarList"
        :now-item="leftActiveTab"
        @changeItem="tabBarChangeItem"
        @openLayoutModal="openBaseLayoutModal"
        v-if="taskLayout == 1"
      ></BaseTileLayoutTabBar>
      <base-collapse
        class="contract-detail-main-content"
        :show-collapse="true"
        :direction.sync="collapseDirection"
        :hidePartCollapse="hidePartCollapse"
      >
        <!-- 左边面板 -->
        <template slot="left">
          <div
            class="contract-detail-main-content-left"
            v-show="collapseDirection != 'left'"
          >
            <BaseTileLayoutTabBar
              :bar-list="leftTabBarList"
              :now-item="leftActiveTab"
              @openLayoutModal="openBaseLayoutModal"
              v-if="taskLayout == 2"
            ></BaseTileLayoutTabBar>
            <div class="content" v-if="leftActiveTab == 'contract-info'">
              <form-view class="bbx-cell-form-view" :form-cell-count="formCellCount" :fields="fields" :value="detailData">
                <!-- 客户 S -->
                <template slot="customer" slot-scope="{ field }">
                  <div class="form-view-row bbx-form-cell-item">
                    <label>{{ field.displayName }}</label>
                    <div class="form-view-row-content link" @click="JumpCustomer(detailData.customer)">
                      {{
                        (detailData.customer && detailData.customer.name) || ''
                      }}
                    </div>
                  </div>
                </template>
                <!-- 客户 E -->

                <!-- 创建人 S  -->
                <template slot="creater" slot-scope="{ field }">
                  <div class="form-view-row bbx-form-cell-item">
                    <label>{{ field.displayName }}</label>
                    <div class="link" v-user="detailData.createUser && detailData.createUser.userId">
                      {{ 
                        (detailData.createUser && detailData.createUser.displayName) || ''  
                      }}
                    </div>
                  </div>
                </template>

                <!-- 数据状态 S -->
                <template slot="contractStatus" slot-scope="{ field }">
                  <div class="form-view-row bbx-form-cell-item">
                    <label>{{ field.displayName }}</label>
                    <span
                      class="status-tab"
                      :style="{
                        background:
                          contractStatusBgc[detailData.contractStatus],
                      }"
                      >{{ getStatusValue[detailData.contractStatus] }}</span
                    >
                  </div>
                </template>
                <!-- 数据状态 E -->

                <!-- 客户联系人 S -->
                <template slot="linkman" slot-scope="{ field }">
                  <div class="form-view-row bbx-form-cell-item">
                    <label>{{ field.displayName }}</label>
                    <div class="form-view-row-content">
                      {{
                        (detailData.customer && detailData.customer.lmName) ||
                        ''
                      }}
                    </div>
                  </div>
                </template>
                <!-- 客户 E -->

                <!-- 服务部门 S -->
                <template slot="tags" slot-scope="{ field }">
                  <div class="form-view-row bbx-form-cell-item">
                    <label>{{ field.displayName }}</label>
                    <div class="form-view-row-content">
                      {{ detailData.tagSimpleVOList | fmt_tag }}
                    </div>
                  </div>
                </template>
                <!-- 服务部门 E -->

                <!-- 金额相关添加币种 S -->
                <template v-for="item in contractAmountFieldNameList" :slot="item" slot-scope="{ field, value }">
                  <div class="form-view-row bbx-form-cell-item">
                    <label>{{ field.displayName }}</label>
                    <div class="form-view-row-content">
                      {{ getCurrencyAmountView(value, item) }}
                    </div>
                  </div>
                </template>
                <!-- 金额相关添加币种 E -->
              </form-view>
            </div>
          </div>
          <div class="extend-btn" v-show="collapseDirection == 'left'">
            {{$t('contract.view.contractInfo')}}
          </div>
        </template>

        <template slot="rightExtend">
          <div class="extend-btn" @click="activeTab = 'info-record'">
            {{$t('common.base.dynamicInfo')}}
          </div>
        </template>

        <!-- 右边面板 -->
        <template slot="right">
          <div
            class="contract-detail-main-content-right"
            v-show="collapseDirection != 'right'"
          >
            <!-- 附加组件筛选 S -->
            <!-- <el-popover
            placement="top-start"
            title="选择显示项"
            popper-class="right-tab-selector-popover"
            trigger="click"
          >
            <el-button
              slot="reference"
              type="ghost"
              class="right-tab-selector"
            >
              <i class="iconfont icon-gaojisousuo"></i>
            </el-button>
            <el-checkbox-group
              v-model="checkList"
              @change="handleCheckChange"
              class="right-tab-selector-group"
            >
              <el-checkbox
                :label="label.key"
                :disabled="label.key === 'info-record'"
                v-for="label in labelAllList"
                :key="label.key"
              >
                {{ label.name }}
              </el-checkbox>
            </el-checkbox-group>
          </el-popover> -->

            <!-- 附加组件筛选 S -->
            <BaseBarV3
              :bar-list="rightTabBarList"
              :now-item="rightActiveTab"
              @changeItem="tabBarChangeItem"
              @upDateBarList="tabBarUpdateList"
              v-if="taskLayout == 2"
            />
            <!-- 动态信息 -->
            <info-record
              v-if="rightActiveTab == 'info-record'"
              :contractId="getContractId"
              @getRecordCount="getRecordCount"
            ></info-record>
            <!-- 计划任务 -->
            <tab-plan-task
              ref="tabPlanTaskRef"
              v-if="rightActiveTab == 'plan-task'"
            ></tab-plan-task>
            <smart-plan-table v-if="rightActiveTab == 'smart-plan-table'" :contract-ids="[getContractId]"></smart-plan-table>
            <!-- 通用日程 -->
            <tab-calendar
              ref="tabCalendarRef"
              v-if="rightActiveTab == 'schedule-reminder'"
            ></tab-calendar>
            <!-- 历史工单 -->
            <history-task
              :contractId="getContractId"
              v-if="rightActiveTab == 'history-task'"
            ></history-task>
          </div>
        </template>
      </base-collapse>
    </template>

    <!-- 审批 -->
    <approve-dialog :approve-data="approveData" ref="approveRef" />
    <!-- 新建智能计划弹窗 -->
    <createSmartPlanDialog :customers="[customerData]" ref="createSmartPlanDialog" />
    <!-- 通栏设置 -->
    <biz-layout-modal
      ref="bizLayoutModal"
      :biz-layout-type="taskLayout"
      :columns="formCellCount"
      @changeLayout="changeTaskDetailLayout">
    </biz-layout-modal>
  </div>
</template>
<script>
import {
  onMounted,
  reactive,
  toRefs,
  ref,
  watch,
  computed,
  nextTick,
  getCurrentInstance,
} from 'vue';
import { MessageBox } from 'element-ui';
import Vue from 'vue';

import Platform from '@src/util/platform.ts';

import platform from '@src/platform';

// api
import {
  contractFieldList,
  getContractDetail,
  deleteContract,
  closeContract,
  checkAuth,
  getTaskTypeList,
} from '@src/api/ContractApi';
// 组件
import InfoRecord from '../components/InfoRecord.vue';
import ApproveDialog from '../components/ApproveDialog.vue';
import noAuth from '@src/modules/calendar/noAuth.vue';
import SmartPlanTable from '@src/modules/smartPlan/common/smartPlanTable.vue'
import TabPlanTask from '../components/TabPlanTask.vue';
import TabCalendar from '../components/TabCalendar.vue';
import HistoryTask from '../components/HistoryTask.vue';
import BaseBarV3 from '@src/component/common/BaseTabBar/BaseTabBarV3.vue'
import BaseTileLayoutTabBar from '@src/component/common/BaseTabBar/BaseTileLayoutTabBar.vue'

import {
  getColumnFields,
  contractStatusBgc,
  getStatusValue,
} from '@src/modules/contract/contractList/fields.js';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
// import { openAccurateTab } from '@src/util/platform'
import i18n from '@src/locales'
/* mixin */
import ManualTriggerMixin from '@src/mixins/manualTriggerMixin'
/* util */
import * as FormUtil from '@src/component/form/util'
import qs from '@src/util/querystring';
import { CURRENCY_SUFFIX, getCurrencyDisplayView, contractAmountFieldNameList } from '@src/util/currency';
import { BaseTabBarUsualEnum, StorageHttpParamsForTerminalType, StorageHttpParamsForModuleType } from '@src/component/common/BaseTabBar/enum'
import { computedTabList } from '@src/util/tabBarUtils'
import { getStorageForDetailTabbar, setStorageForDetailTabbar } from '@src/api/SystemApi'
import { cloneDeep } from 'lodash'
import { useStateSystemViewLayout } from 'pub-bbx-utils'
const { getSystemViewLayout } = useStateSystemViewLayout()
// 国际化灰度
import useFormMultiLanguage from '@hooks/useFormMultiLanguage'
const { internationalGray } = useFormMultiLanguage();

export default {
  mixins: [ManualTriggerMixin],
  components: {
    InfoRecord,
    ApproveDialog,
    noAuth,
    SmartPlanTable,
    TabPlanTask,
    TabCalendar,
    HistoryTask,
    BaseBarV3,
    BaseTileLayoutTabBar,
  },

  filters: {
    fmt_tag(value) {
      if (!Array.isArray(value) || !value || !value.length) return '';
      return value.map(t => t.tagName).join('， ');
    },
  },
  setup() {
    const approveRef = ref(null);
    const tabCalendarRef = ref(null);
    const tabPlanTaskRef = ref(null);
    const bizLayoutModal = ref(null)
    const formCellCount = ref(1)
    const Track = Vue.prototype.$track;

    const state = reactive({
      fields: [],
      detailData: {},
      approveData: {},
      activeTab: 'info-record',
      taskTypes: [],
      labelAllList: [],
      checkList: [],

      certificateList: [], // 回款凭证列表
      planList: [], // 回款计划列表
      collapseDirection: '',
      showLoading: false,
      tabCount: {
        infoCount: 0,
      },
      isCheck: false,
      buttonAuth: {
        update: false,
        deleted: false,
        close: false,
        check: true,
        planTaskAdd: false,
        calendarAdd: false,
      }, // 按钮权限
      isClose: false,
      tabMap: {
        'info-record': '动态信息',
        'plan-task': '计划任务',
        'schedule-reminder': '通用日程',
      },
      pageLoading: false,
    });

    // 合同id
    const getContractId = computed(() => {
      return location.pathname.split('/contract/view/')[1] || '';
    });

    const editBtnAuth = computed(() => {
      return state.buttonAuth.update && state.isClose;
    });

    const closeBtnAuth = computed(() => {
      return state.buttonAuth.close && state.isClose;
    });

    const planBtnAuth = computed(() => {
      return state.buttonAuth.planTaskAdd && state.isClose;
    });

    // 新建日程
    const calendarBtnAuth = computed(() => {
      return state.buttonAuth.calendarAdd && state.isClose;
    });

    // 合同模板id
    const contractTemplateId = computed(() => {
      let query = qs.parse(window.location.search)
      return query.contractTemplateId;
    })

    // ????
    state.collapseDirection =
      sessionStorage.getItem(
        `contract_collapseDirection_${getContractId.value}`
      ) || '';

    // 缓存折叠面板
    watch(
      () => state.collapseDirection,
      (newValue, oldValue) => {
        if (state.activeTab == 'schedule-reminder') {
          nextTick(() => {
            // 切换左右箭头的时候重新渲染下日历，不然样式会错乱
            tabCalendarRef.value?.value === '2' &&
              tabCalendarRef.value?.renderCalendar();
          });
        }
        if (state.activeTab == 'plan-task') {
          nextTick(() => {
            tabPlanTaskRef.value?.value === '2' &&
              tabPlanTaskRef.value?.renderCalendar();
          });
        }
        sessionStorage.setItem(
          `contract_collapseDirection_${getContractId.value}`,
          newValue
        );
      }
    );

    watch(
      () => state.activeTab,
      (newValue, oldValue) => {
        Track.clickStat(Track.formatParams('DETAIL_ADD_ONS_TABS', state.tabMap[newValue]))
      }
    );

    // 获取按钮权限
    const getBtnAuth = () => {
      return checkAuth({
        contractId: getContractId.value,
      }).then(res => {
        if (!res.success) return Platform.toast(res.message, 'error');
        state.buttonAuth = { ...res.result };
      });
    };

    // 获取表单字段
    const fetchFields = async () => {
      state.showLoading = true;
      try {
        let ret = await contractFieldList({
          templateId: contractTemplateId.value
        });
        state.fields = ret.success ? [...ret.result, ...getColumnFields()] : [];
      } catch (err) {
        console.log('error => fetchFields', err);
      } finally {
        // state.showLoading = false;
      }
    };

    /**
     * @description 获取Field
     */
    const getField = type => {
      let field = state.fields.filter(item => item.formType == type)[0];
      return field;
    };

    // 获取详情数据
    const fetchContractList = () => {
      state.showLoading = true;
      getContractDetail({
        contractId: getContractId.value,
      }).then(async res => {
        if (res.success) {
          let attribute = {};

          const { productList, productWarrantyList, sparepartList } = res.result || {};
          let productField = getField('product'); // 产品
          let sparePartField = getField('subSparePart'); // 备件
          let productWarrantyServiceField = getField('productWarrantyService'); // 产品质保服务

          let obj = {};
          obj[productField?.fieldName] = productList;
          obj[sparePartField?.fieldName] = sparepartList;
          obj[productWarrantyServiceField?.fieldName] = productWarrantyList;

          // 处理富文本
          res.result = await FormUtil.initRichTextContent(state.fields, res.result)
          
          attribute = {
            ...res.result.attribute,
            ...obj,
          };

          delete res.result.attribute;

          state.detailData = { attribute, ...res.result };

          state.isClose = state.detailData?.contractStatus != 'CLOSED';

          let id = window.frameElement.dataset.id;
          platform.setTabTitle({
            id,
            title: `${i18n.t('contract.view.contractDetail')} - ${state.detailData.contractName}`,
          });
        } else {
          return Platform.toast(res.message, 'error');
        }
      }).finally (() => {
        state.showLoading = false;
      })
    };

    // 刷新tab
    const reloadTab = () => {
      let id = window.frameElement?.dataset?.id;
      let fromId = window.frameElement?.getAttribute('fromid');

      // 打开相应的tab 关闭当前tab
      platform.refreshTab(fromId);
      platform.closeTab(id);
      platform.goOpenTab(fromId);
    };

    /** 编辑 */
    const handleEdit = () => {
      Track.clickStat(getBtnsTrackData('TO_EDIT'));
      
      let { templateId } = state.detailData || {};

      let id = window.frameElement?.dataset?.id;
      let fromId = window.frameElement.getAttribute('id');

      platform.closeTab(id);

      Platform.openAccurateTab({
        type: PageRoutesTypeEnum.PageEditContract,
        key: getContractId.value,
        reload: true,
        params: `contractTemplateId=${templateId}`,
        fromId,
      })
    };

    /** 删除 */
    const handleClickDelete = () => {
      Track.clickStat(getBtnsTrackData('DELETE'));

      MessageBox.confirm(
        i18n.t('contract.delContract.confirm.msg'),
        i18n.t('contract.delContract.confirm.title'),
        {
          type: 'warning',
        }
      )
        .then(() => {
          // 删除接口
          deleteContract([getContractId.value]).then(res => {
            if (!res.success) {
              return Platform.toast(res.message, 'error');
            }

            Platform.toast(i18n.t('common.base.deleteSuccess'), 'success');

            setTimeout(() => {
              reloadTab();
            }, 300);
          });
        })
        .catch(err => {});
    };

    /** 关闭 */
    const handleClickClose = () => {
      Track.clickStat(getBtnsTrackData('CLOSE'));

      MessageBox.confirm(
        i18n.t('contract.closeContract.confirm.msg'),
        i18n.t('contract.closeContract.confirm.title'),
        {
          type: 'warning',
        }
      )
        .then(() => {
          // 关闭接口
          closeContract({
            contractId: getContractId.value,
          }).then(res => {
            if (!res.success) {
              return Platform.toast(res.message, 'error');
            }
            reloadTab();
          });
        })
        .catch(err => {});
    };

    /** 审批 */
    const handleApprove = () => {
      approveRef.value.visible = true;
    };

    /** 撤回 */
    const handleWithdraw = () => {
      console.log('handleWithdraw');
    };

    // 获取计划任务列表数据
    const fetchTaskPlanList = () => {
      getTaskTypeList().then(res => {
        if (!res.success) {
          return Platform.toast(res.message, 'error');
        }
        state.taskTypes = res.result;
      });
    };

    // 点击日程提醒 - 跳转日程
    const JumpCalendar = () => {
      Track.clickStat(getBtnsTrackData('CREATE_CALENDAR'));

      let fromId = window.frameElement.getAttribute('id');

      Platform.openAccurateTab({
        type: PageRoutesTypeEnum.PageSchedule,
        params: `type=create&objectType=1&objectId=${getContractId.value}`,
        reload: true,
        fromId,
      })
    };

    const getRecordCount = value => {
      state.tabCount.infoCount = value;
      const idx = bannerState.rightTabBarList.findIndex(
        item => item.tabName === 'info-record'
      );
      if (idx != -1){
        bannerState.rightTabBarList[idx].tabLabel = i18n.t('common.base.dynamicInfo')+`(${value})`
      }
    };

    // 点击跳转工单计划任务
    const jumpTaskPlan = typeId => {
      Track.clickStat(getBtnsTrackData('CREATE_PLAN_TASK'));

      let fromId = window.frameElement.getAttribute('id');

      Platform.openAccurateTab({
        type: PageRoutesTypeEnum.PagePlanTaskCreate,
        params: `defaultTypeId=${typeId}&contractId=${getContractId.value}`,
        fromId,
      })
    };

    // 跳转客户详情
    const JumpCustomer = (customer) => {
      const customerId = customer.id || '';

      if(!customerId.length) return;

      Platform.openAccurateTab({
        type: PageRoutesTypeEnum.PageCustomerView,
        key: customerId,
        params: 'noHistory=1',
      })
    }
    // change附加组件筛选
    const handleCheckChange = () => {};

    const getBtnsTrackData = (id, data) => {
      return Track.formatParams(id, data, 'DETAIL_BTNS_GROUP');
    };

    /* ----------币种相关 start---------- */
    const getCurrencyAmountView = (value, name) => {
      if(!internationalGray) return value;

      const params = {
        number: value, 
        currency: state.detailData[name + CURRENCY_SUFFIX] || 'CNY'
      }
      return getCurrencyDisplayView(params);
    }
    /* ----------币种相关 end---------- */

   /* ----------通栏 start---------- */
    const bannerState = reactive({
      taskLayout: 2, // 布局方式 1:通栏 2:左右 
      leftActiveTab: '',
      leftActiveTabItem: {},
      rightActiveTab: '',
      rightActiveTabItem: {},
      tabPosition: '', // 记录tab位置  left|right
      leftTabBarList : [],
      rightTabBarList : [],
      taskLayoutTabBarList: []
    })

    const hidePartCollapse = computed(() => {
      if(bannerState.taskLayout === 2) return '';

      if(bannerState.taskLayout === 1) {
        return bannerState.tabPosition === 'left' ? 'right' : 'left';
      }
    })

    async function initBanner(vm) {
      try {
        const count = await getSystemViewLayout()
        bannerState.taskLayout = count?.baseLayout || 2
        formCellCount.value = count?.formCellCount || 1
      } catch (error) {
        console.warn(error, 'error try catch initBanner');
      }
      // 通栏模式tabPosition默认left
      if (bannerState.taskLayout === 1) {
        bannerState.tabPosition = 'left'
      }
      let leftTabBarList = [
        { position: 'left', tabLabel:i18n.t('contract.view.contractInfo'), tabName: 'contract-info', tabShow: true},
      ]
      let rightTabBarList = [
        { position: 'right', tabLabel:i18n.t('common.base.dynamicInfo')+`(${state.tabCount.infoCount})`, tabName: 'info-record', tabShow: true, disabled: true}, // 动态信息
        ...(vm.buttonAuth?.planTaskAdd && !vm.smartPlanGray ? [{ position: 'right', tabLabel:i18n.t('contract.view.scheduledTasks'), tabName: 'plan-task', tabShow: true}] : []), // 任务计划
        ...(vm.smartPlanGray ? [{ position: 'right', tabLabel:i18n.t('smartPlan.title'), tabName: 'smart-plan-table', tabShow: true}] : []), // 智能计划
        { position: 'right', tabLabel:i18n.t('contract.view.scheduleReminder'), tabName: 'schedule-reminder', tabShow: true}, // 通用日程
        { position: 'right', tabLabel:i18n.t('im.imChat.components.seviceRecords.des2'), tabName: 'history-task', tabShow: true}, // 历史工单
      ]
      // 没权限过滤掉任务计划
      if (!state.buttonAuth.planTaskAdd) {
        rightTabBarList = rightTabBarList.filter(v=>v.tabName !='plan-task')
      }
      // 过滤掉通用日程
      if (!state.buttonAuth.calendarView) {
        rightTabBarList = rightTabBarList.filter(v=>v.tabName !='schedule-reminder')
      }

      // 读取缓存tabbar修改右栏tabbar配置
      try {
        let { TabBarListItemKey:tabName, TabBarListItemShow:tabShow} = BaseTabBarUsualEnum;
        let parasm_ = {
          equipment:StorageHttpParamsForTerminalType.PC,
          bizType:StorageHttpParamsForModuleType.Task,
          bizTypeId:`contract_${getContractId.value}`
        }
        // 获取tabbar用户行为缓存/*  */
        let storageList = await getStorageForDetailTabbar(parasm_);
        if(storageList.status !== 0) {
          throw storageList.message
        }
        let storageList_ = storageList.data.map(item=>{
          const { cardId, checked} = item;
          return {
            [tabName]:cardId,
            [tabShow]:checked
          }
        })
        rightTabBarList = computedTabList(rightTabBarList, storageList_)
        console.log(rightTabBarList, 'rightTabBarList');
      } catch (error) {
        console.warn(error, 'error try catch getStorageForDetailTabbar');
      }

      bannerState.leftActiveTab = leftTabBarList[0].tabName
      bannerState.leftActiveTabItem = leftTabBarList[0]
      bannerState.leftTabBarList = leftTabBarList
      bannerState.rightActiveTab = rightTabBarList[0].tabName
      bannerState.rightActiveTabItem = rightTabBarList[0]
      bannerState.rightTabBarList = rightTabBarList
    }

    watch(
      ()=>[bannerState.leftTabBarList, bannerState.rightTabBarList], ([newValue1,newValue2]) => {
        bannerState.taskLayoutTabBarList = cloneDeep([...newValue1,...newValue2].filter(item => item.tabShow));
      },
      {
        deep: true
      }
    )

    function tabBarChangeItem (item) {
      let { TabBarListItemKey:tabName } = BaseTabBarUsualEnum;
      let { position } = item
      bannerState.tabPosition = position
      // 通栏导航和左侧导航共用leftActiveTab数据
      if (bannerState.taskLayout === 1 || position == 'left') {
        bannerState.leftActiveTab = item[tabName];
        bannerState.leftActiveTabItem = item
      }
      // 右侧导航
      if (position == 'right') {
        bannerState.rightActiveTab = item[tabName];
        bannerState.rightActiveTabItem = item
      }
    }

    function tabBarUpdateList(list) {
      const { TabBarCardInfoType, TabBarListItemKey:tabName, TabBarListItemShow:tabShow } = BaseTabBarUsualEnum;
      let list_ = list.map(item=>{
        return {
          cardId: item.type == TabBarCardInfoType ? item.id : item[tabName],
          checked: item[tabShow]
        }
      })
      let params = {
        equipment:StorageHttpParamsForTerminalType.PC,
        bizType:StorageHttpParamsForModuleType.Task,
        bizTypeId: `contract_${getContractId.value}`,
        cardList:list_
      }
      // 存储右栏tabbar
      setStorageForDetailTabbar(params)
    }

    function openBaseLayoutModal() {
      bizLayoutModal.value.open()
    }

    function changeTaskDetailLayout(type, columns) {
      bannerState.leftActiveTab = bannerState.leftTabBarList[0].tabName
      bannerState.leftActiveTabItem = bannerState.leftTabBarList[0] 
      bannerState.taskLayout = type
      bannerState.tabPosition = 'left'
      if (type === 2) {
        bannerState.rightActiveTab = bannerState.rightTabBarList[0].tabName
        bannerState.rightActiveTabItem = bannerState.rightTabBarList[0]
      }
      formCellCount.value = columns * 1
    }
   /* ----------通栏 end---------- */

    onMounted(async () => {
      try {
        const vm = getCurrentInstance().proxy;
        state.pageLoading = true;
        await getBtnAuth();
        await fetchFields();
        await fetchContractList();
        await fetchTaskPlanList();
        await initBanner(vm);
      } catch (error) {
        console.warn(error, 'error try catch onMounted');
      } finally {
        state.pageLoading = false;
      }
    });

    return {
      approveRef,
      ...toRefs(state),
      handleApprove,
      handleWithdraw,
      jumpTaskPlan,
      handleCheckChange,
      handleEdit,
      handleClickDelete,
      handleClickClose,
      getContractId,
      getRecordCount,
      JumpCalendar,
      tabCalendarRef,
      tabPlanTaskRef,
      planBtnAuth,
      calendarBtnAuth,
      editBtnAuth,
      closeBtnAuth,
      contractStatusBgc,
      getStatusValue,
      JumpCustomer,
      contractAmountFieldNameList,
      getCurrencyAmountView,
      ...toRefs(bannerState),
      tabBarChangeItem,
      tabBarUpdateList,
      openBaseLayoutModal,
      changeTaskDetailLayout,
      bizLayoutModal,
      hidePartCollapse,
      formCellCount,
    };
  },
  computed: {
    // 是否显示更多操作
    isShowMoreOperation() {
      return this.isShowCreateSmartPlan
    },
    customerData() {
      return this.detailData?.customer
    },
  },
  methods: {
    handleMoreOperationCommand(command) {
      if (command == 'smartPlan') {
        this.$refs.createSmartPlanDialog.open()
      }
    }
  }
};
</script>
<style lang="scss">
.theme-default {
  padding: 12px;
}
.detail-more-dropdown-menu .el-dropdown-menu__item {
  width: initial;
  max-width: 180px;
  @include text-ellipsis();
}
</style>
<style lang="scss" scoped>
.contract-view {
  width: 100%;
  min-width: 1100px;
  height: 100%;
  display: flex;
  flex-flow: column nowrap;
  overflow: hidden;
  &-title {
    height: 60px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #ffffff;
    border-radius: 4px;
    box-shadow: 0px 2px 8px 0px rgba(0, 0, 0, 0.1);
    padding: 0 16px;
    margin-bottom: 12px;
    &-left {
      display: flex;
      align-items: center;
    }
  }

  .contract-detail-main-content {
    flex: 1;

    &-left,
    &-right {
      border-radius: inherit;
      height: 100%;
      overflow: hidden;
    }

    &-left {
      display: flex;
      flex-direction: column;
      .title {
        height: 40px;
        line-height: 40px;
        background: #fafafa;
        padding-left: 16px;
        font-size: 16px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #262626;
        border-bottom: 1px solid #e8e8e8;
        border-radius: 4px 4px 0 0;
      }
      .content {
        overflow: auto;
        padding: 16px;
      }
      .status-tab {
        display: inline-block;
        min-width: 52px;
        max-width: 128px;
        height: 22px;
        line-height: 22px;
        padding: 0 8px;
        font-size: 12px;
        border-radius: 11px;
        text-align: center;
        vertical-align: middle;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        color: #fff;
      }
    }
    &-right {
      height: 100%;
      overflow: hidden;
      ::v-deep .el-tabs {
        height: 100%;
        overflow: hidden;

        &__header {
          background: #fafafa;
          width: 100%;

          .el-tabs__item {
            color: $text-color-regular;
            &.is-active {
              @include fontColor();
            }
          }
        }
        &__nav-wrap {
          padding-left: 16px;
        }

        &__content {
          height: calc(100% - 56px);
          // overflow-y: auto;
          padding: 0;
          #pane-schedule-reminder {
            overflow: hidden;
          }
          .el-tab-pane {
            height: 100%;
          }
        }
      }
    }
    .extend-btn {
      height: 40px;
      line-height: 40px;
      background: #fafafa;
      padding-left: 16px;
      border-bottom: 1px solid #e4e7ed;
    }
  }
}
.plan-dropdown-item {
  color: #262626;
  display: block;
  &:hover {
    text-decoration: none;
  }
}
.link {
  color: $color-primary-light-6;
  cursor: pointer;
  &:hover {
    text-decoration: underline;
  }
}
.smart-plan-table {
  padding: 0;
}
</style>